"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Search, CheckCircle } from "lucide-react";

interface Feedback {
  feedbackId: number;
  openId: string;
  feedbackContent: string;
  feedbackTime: string;
  feedbackState: number;
  userName: string;
  userAvatar: string;
}

export default function FeedbacksPage() {
  const [feedbacks, setFeedbacks] = useState<Feedback[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchFeedbacks = async () => {
      try {
        setIsLoading(true);
        const response = await fetch("/api/feedbacks");

        if (!response.ok) {
          throw new Error("获取反馈数据失败");
        }

        const data = await response.json();
        setFeedbacks(data.feedbacks);
      } catch (error) {
        console.error("获取反馈数据失败:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchFeedbacks();
  }, []);

  // 处理反馈状态更新
  const handleUpdateFeedbackState = async (
    feedbackId: number,
    newState: number
  ) => {
    try {
      const response = await fetch("/api/feedbacks", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          feedbackId,
          feedbackState: newState,
        }),
      });

      if (!response.ok) {
        throw new Error("更新反馈状态失败");
      }

      // 更新本地状态
      setFeedbacks(
        feedbacks.map((feedback) =>
          feedback.feedbackId === feedbackId
            ? { ...feedback, feedbackState: newState }
            : feedback
        )
      );
    } catch (error) {
      console.error("更新反馈状态失败:", error);
      alert("更新反馈状态失败");
    }
  };

  // 过滤反馈
  const filteredFeedbacks = feedbacks.filter(
    (feedback) =>
      feedback.feedbackContent
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||
      feedback.userName.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">反馈管理</h1>
        <p className="text-muted-foreground">查看和处理用户反馈信息</p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">反馈列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索反馈..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>用户</TableHead>
                  <TableHead>反馈内容</TableHead>
                  <TableHead>提交时间</TableHead>
                  {/* <TableHead>状态</TableHead>
                  <TableHead className="text-right">操作</TableHead> */}
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredFeedbacks.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center h-24">
                      未找到匹配的反馈
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredFeedbacks.map((feedback) => (
                    <TableRow key={feedback.feedbackId}>
                      <TableCell className="font-medium">
                        <div className="flex items-center space-x-2">
                          <img
                            src={feedback.userAvatar}
                            alt={feedback.userName}
                            className="h-8 w-8 rounded-full"
                          />
                          <span>{feedback.userName}</span>
                        </div>
                      </TableCell>
                      <TableCell className="max-w-md truncate">
                        {feedback.feedbackContent}
                      </TableCell>
                      <TableCell>{formatDate(feedback.feedbackTime)}</TableCell>
                      {/* <TableCell>
                        <Badge
                          variant={
                            feedback.feedbackState === 0
                              ? "secondary"
                              : "success"
                          }
                        >
                          {feedback.feedbackState === 0 ? "未处理" : "已处理"}
                        </Badge>
                      </TableCell> */}
                      {/* <TableCell className="text-right">
                        {feedback.feedbackState === 0 ? (
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={() => handleUpdateFeedbackState(feedback.feedbackId, 1)}
                          >
                            <CheckCircle className="mr-2 h-4 w-4" />
                            标记为已处理
                          </Button>
                        ) : (
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => handleUpdateFeedbackState(feedback.feedbackId, 0)}
                          >
                            重置为未处理
                          </Button>
                        )}
                      </TableCell> */}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
